package top.code.login.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.code.common.utils.SecurityUtils;
import top.code.user.entity.User;
import top.code.user.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
*@Author benson {www.honey520.com}
*@Date 2017/9/21 21:04
*@Description
*/
@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private UserService userService;
    /**
     *@Author benson {www.honey520.com}
     *@Date 2017/9/21 21:04
     *@Description
     */
    @RequestMapping
    public String login() {

        return "login";
    }

    /**
     *@Author benson {www.honey520.com}
     *@Date 2017/9/21 21:05
     *@Description  校验登陆
     */
    @RequestMapping("/check")
    @ResponseBody
    public String checkLogin(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String username = request.getParameter("username");
        String pwd = request.getParameter("password");
        //查数据库  调用md5  如果校验成功
        User user = userService.findUserByUserName(username);
        if(user != null){
           if(SecurityUtils.checkPassword(pwd,user.getPassword())){
               //检查用户成功 用户信息存session 返回signal 异步
               request.getSession().setAttribute("userinfo",user);
               return "login_succ"; //成功返回succ
           }else{
               //校验失败 提示 异步
               return "login_fail";
           }
        }else{
            return "login_fail";    //没有用户  返回fail
        }
    }



    @RequestMapping("/register")
    @ResponseBody
    public String register(@RequestBody User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        userService.createUser(user);

        return "succ";
    }


}